# -*- coding: utf-8 -*-

'''eof
name:申请企业未来6个月到期贷款金额
code:EC110_Ent6MonsExpLoanAmt
tableName:
columnName:
groups:企业征信
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:申请企业未来6个月到期贷款金额
eof'''

import pandas as pd

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

# 获取表信息方法
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


# 时间信息格式化方法
def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


# 数值判断方法
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def EC110_Ent6MonsExpLoanAmt():
    try:
        factor = []
        data = EC_DSJ_2D['data']
        # 信用提示信息
        EDA = getTable(data, 'EDA', 1, 0)
        if EDA == [{}]:
            factor.append(None)
        elif EDA == 0:
            factor.append(0)
        else:
            ED01 = getTable(EDA[0], 'ED01', 0, 1)
            if ED01 == 0:
                factor.append(0)
            elif ED01 == [{}]:
                factor.append(None)
            else:
                for i in ED01:
                    try:
                        #  基本信息段
                        ED01A = getTable(i, 'ED01A', 1, 1)
                        if ED01A == 0:
                            factor.append(0)
                        elif ED01A == [{}]:
                            factor.append(None)
                        else:
                            # 账户活动状态
                            ED01AD01 = ED01A[0].get('ED01AD01')
                            # 借贷业务种类大类
                            ED01AD05 = ED01A[0].get('ED01AD05')
                            # 借贷业务种类细分
                            ED01AD06 = ED01A[0].get('ED01AD06')
                            # 到期日期
                            ED01AR02 = ED01A[0].get('ED01AR02')
                            # 借款金额
                            ED01AJ01 = ED01A[0].get('ED01AJ01')
                            # 报告日期
                            ED01AR04 = ED01A[0].get('ED01AR04')
                            if ED01AD01 in null_type_list or ED01AD05 in null_type_list or ED01AD06 in null_type_list \
                                    or dateFormat(ED01AR02) is None or isfloat(ED01AJ01) is False or dateFormat(ED01AR04) is None:
                                factor.append(None)
                            else:
                                aaa = [
                                    (dateFormat(ED01AR02) + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d')
                                    for i in [-6, 0]]
                                if str(ED01AD01) == '1' and str(ED01AD05) == '11' \
                                    and str(ED01AD06) in ['11', '12', '13', '14', '15', '16', '17', '90'] \
                                    and aaa[0] <= dateFormat(ED01AR04).strftime('%Y%m%d') and dateFormat(ED01AR04).strftime('%Y%m%d') < aaa[1]:
                                    factor.append(float(ED01AJ01))
                                else:
                                    factor.append(0)
                    except:
                        factor.append(None)
                        continue
        factorNotNone = list(filter(lambda x: x is not None, factor))
        if len(factorNotNone) == 0:
            return u'缺失值'
        else:
            return sum(factorNotNone)
    except:
        return u"缺失值"


result = EC110_Ent6MonsExpLoanAmt()

